﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.Abstract;
using System.Data.Linq;
using System.Configuration;
using System.Diagnostics;

namespace DomainModel.Concrete
{
    public class OrderRepository:IOrderRepository
    {
        private Table<Order> ordersTable;
        private DataContext dataContext;
        public object Locker { get; set; }


        public OrderRepository()
        {
            
            String cs = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();
            dataContext = new DataContext(cs);
            ordersTable = dataContext.GetTable<Order>();
            Locker = new object();        
        }

        public IQueryable<Order> Orders
        {
            get { return ordersTable; }
        }

        public Order GetOrder(Int32 id)
        {
            try
            {
                return ordersTable.First(d => d.OrderID == id);
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        public void Add(Order o)
        {
            try
            {
                ordersTable.InsertOnSubmit(o);
            }
            catch (Exception exc)
            {

            }
        }

        public void Delete(Order o)
        {
            ordersTable.DeleteOnSubmit(o);
        }

        public void Save()
        {
            lock (this.Locker)
            {
                ordersTable.Context.SubmitChanges();
                ordersTable.Context.Refresh(RefreshMode.OverwriteCurrentValues, ordersTable);
                Repositories.VOrderRepository.RefreshContext();
            }
        }
    }
}
